package com.hust.query.dian.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.devspark.appmsg.AppMsg;
import com.hust.query.dian.CMApplication;
import com.hust.query.dian.R;
import com.hust.query.dian.utils.ActivityUtils;
import com.hust.query.dian.utils.CommonUtils;
import com.hust.query.dian.utils.LogUnit;
import com.hust.query.dian.widget.magic.MagicScrollView;
import com.hust.query.dian.widget.magic.MagicTextView;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.umeng.fb.SyncListener;
import com.umeng.fb.model.Conversation;
import com.umeng.fb.model.Reply;
import com.umeng.update.UmengUpdateAgent;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static com.devspark.appmsg.AppMsg.LENGTH_STICKY;

public class MainActivity extends AppCompatActivity implements Handler.Callback, View.OnClickListener,PopupMenu.OnMenuItemClickListener,
        View.OnCreateContextMenuListener {

    private MagicScrollView mScrollView;
    private MagicTextView mIncomeTxt;
    private LinearLayout xmLay1,xmLay2,xmLay3,alt_parent;
    private Button queryBtn, cleanBtn;
    private ProgressDialog pDialog;
    private TextView txt1,txt2,txt3;
    private Handler mHandler;
    public AppMsg.Style style;
    public AppMsg provided = null;
    public AppMsg appMsg;

    int[] location = new int[2];
    public static int mWinheight;

    private static final int INTERVAL_TIME = 5;
    private static final int MILLISECOND_TO_SECOND = 1000;
    private boolean mIsExit;
    private static long sFirstTimePressBackBtn;
    private FeedbackAgent fb = null;

    public String UniUrl = "http://202.114.18.218/main.aspx";
    public String reqContent="", viewState="", eventVALIDATION = "";

    public final String RequestMethodPost = "POST";
    public final String RequestMethodGet = "GET";

    public List<String> popList1 = new ArrayList<String>();  //存放区域数组
    public List<String> popList2 = new ArrayList<String>();  //存放楼栋数组

    public final int Code_Text_Animation            = 4421;
    public final int Code_Temp_1                    = 1001;
    public final int Code_Temp_2                    = 1002;
    public final int Code_Temp_3                    = 1003;
    public final int Code_Temp_4                    = 1004;
    public final int Code_Temp_5                    = 1005;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);

        if ( !CommonUtils.isNetWorkConnected(this) ){
            Toast.makeText(this,"网络不通,请检查网络情况", Toast.LENGTH_SHORT).show();
            finish();
        }

        mHandler = new Handler(this);
        initUI();

        fb = new FeedbackAgent(MainActivity.this);
//        fb.sync();

        Conversation conversation = fb.getDefaultConversation();
        conversation.sync(new SyncListener() {
            @Override
            public void onReceiveDevReply(List<Reply> replyList) {
                if (replyList == null || replyList.size() < 1) {
                    return;
                }else {
                    showSearchTips("管理员有新的回复");
                }
            }

            @Override
            public void onSendUserReply(List<Reply> list) {

            }
        });

        if ( CMApplication.getInstance().userPrefer.getBoolean("autoload", false) ){
            //如果是true，则自动加载上次的房间
            pDialog.show();
            txt1.setText(CMApplication.getInstance().userPrefer.getString("programId", ""));
            txt2.setText(CMApplication.getInstance().userPrefer.getString("txtyq", ""));
            txt3.setText(CMApplication.getInstance().userPrefer.getString("Txtroom", ""));
            autoThead();

        }else {
            pDialog.show();
            doThread(1);
        }

        //自动升级
        UmengUpdateAgent.update(this);
    }

    public void onResume() {
        super.onResume();
        //umeng统计
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        //umeng统计
        MobclickAgent.onPause(this);
    }

    public void initUI(){
        Rect fram = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(fram);
        mWinheight = fram.height();

        mScrollView = (MagicScrollView) findViewById(R.id.magic_scroll);
        mIncomeTxt = (MagicTextView) findViewById(R.id.income_money);
        mScrollView.AddListener(mIncomeTxt);

        alt_parent = (LinearLayout) findViewById(R.id.alt_parent);
        xmLay1 = (LinearLayout) findViewById(R.id.xmLay1);
        xmLay2 = (LinearLayout) findViewById(R.id.xmLay2);
        xmLay3 = (LinearLayout) findViewById(R.id.xmLay3);
        queryBtn = (Button) findViewById(R.id.queryBtn);
        cleanBtn = (Button) findViewById(R.id.cleanBtn);
        txt1 = (TextView) findViewById(R.id.txt1);
        txt2 = (TextView) findViewById(R.id.txt2);
        txt3 = (TextView) findViewById(R.id.txt3);
        ImageView popmenu = (ImageView) findViewById(R.id.popMenu);
        popmenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopmenu(view);
            }
        });

        xmLay1.setOnClickListener(this);
        xmLay2.setOnClickListener(this);
        xmLay3.setOnClickListener(this);
        queryBtn.setOnClickListener(this);
        cleanBtn.setOnClickListener(this);
        alt_parent.setOnClickListener(this);

        pDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
        pDialog.setMessage("加载中...");
        pDialog.setCanceledOnTouchOutside(false);
        pDialog.setCancelable(false);
    }

    public void showPopmenu(View v) {
        PopupMenu popup = new PopupMenu(this, v);
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.menu_main, popup.getMenu());
        popup.setOnMenuItemClickListener(this);
        popup.show();
    }

    public void showSearchTips(String searchContent){
        style = new AppMsg.Style(LENGTH_STICKY, R.color.sticky);
        provided = AppMsg.makeText(this, searchContent, style, R.layout.sticky);
        provided.getView()
                .findViewById(R.id.remove_btn)
                .setOnClickListener(new CancelAppMsg(provided));
        provided.getView().findViewById(android.R.id.message).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                provided.cancel();
                alt_parent.setVisibility(View.GONE);
                ActivityUtils.jump(MainActivity.this, CustomActivity.class, 0);
            }
        });

        appMsg = provided != null ? provided : AppMsg.makeText(this, searchContent, style);
        appMsg.setParent(alt_parent);
        alt_parent.setVisibility(View.VISIBLE);
        appMsg.show();
    };

    class CancelAppMsg implements View.OnClickListener {
        private final AppMsg mAppMsg;

        CancelAppMsg(AppMsg appMsg) {
            mAppMsg = appMsg;
        }

        @Override
        public void onClick(View v) {
            mAppMsg.cancel();
            alt_parent.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                Toast.makeText(MainActivity.this, "暂时没有", Toast.LENGTH_SHORT).show();
                break;

            case R.id.action_about:
                ActivityUtils.jump(MainActivity.this, AboutWeixun.class, 0);
                break;

            case R.id.action_feedback:
                ActivityUtils.jump(MainActivity.this, CustomActivity.class, 0);
                break;

            default:
                break;
        }
        return false;
    }

    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN ) {
            if ( event.getKeyCode() == KeyEvent.KEYCODE_BACK ){
                if (!mIsExit) {
                    Toast.makeText(this, getText(R.string.str_again_exit), Toast.LENGTH_SHORT).show();
                    mIsExit = true;
                    sFirstTimePressBackBtn = System.currentTimeMillis();
                } else {
                    long interval = (System.currentTimeMillis() - sFirstTimePressBackBtn) / MILLISECOND_TO_SECOND;
                    if (interval < INTERVAL_TIME) {
                        finish();

                    } else {
                        mIsExit = false;
                        Toast.makeText(this, getText(R.string.str_again_exit), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            return false;
        }
        return super.dispatchKeyEvent(event);
    };


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void onMeasureTxt(MagicTextView view) {
        view.getLocationInWindow(location);
        view.setLocHeight(location[1]);
    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    public String doPost(String m, String content){
        String response = "";
        try {
            URL url = new URL(UniUrl);
            HttpURLConnection uRLConnection = (HttpURLConnection) url.openConnection();
            uRLConnection.setDoInput(true);
            uRLConnection.setDoOutput(true);
            uRLConnection.setRequestMethod(m);
            uRLConnection.setUseCaches(false);
            uRLConnection.setInstanceFollowRedirects(false);
            uRLConnection.setRequestProperty("User-agent", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
            uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            uRLConnection.connect();

            DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
            out.writeBytes(content);
            out.flush();
            out.close();

            InputStream is = uRLConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            String readLine = null;
            while((readLine =br.readLine()) != null){
                //response = br.readLine();
                response = response + readLine;
            }
            is.close();
            br.close();
            uRLConnection.disconnect();
            return response;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return response;
        } catch (IOException e) {
            e.printStackTrace();
            return response;
        }
    }


    public void autoThead(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                //------------------------此处同doThread(1)------------------------------
                pFun1(0);

                //------------------------此处同doThread(2)------------------------------
                pFun2(0);

                //------------------------此处同doThread(3)------------------------------
                pFun3(0);

                //------------------------此处同doThread(4)------------------------------
                pFun4();

            }
        }).start();
    }

    public void doThread(final int index){
        new Thread(new Runnable() {
            @Override
            public void run() {
                if ( 1 == index ){//查询是哪个区域
                    pFun1(1);

                }else if ( 2 == index ){//查询是哪一栋楼
                    pFun2(1);

                }else if ( 3 == index ){//查询最终的viewState和eventVALIDATION
                    pFun3(1);

                }else if ( 4 == index ){//查询出剩余电量
                    pFun4();

                }
            }
        }).start();
    }

    public void pFun1(int isDis){
        reqContent = "";
        Document mDocument = Jsoup.parse(doPost(RequestMethodGet, reqContent));
        Elements divs = mDocument.select("#programId");
        Document divcontions = Jsoup.parse(divs.toString());
        Elements element = divcontions.getElementsByTag("option");

        viewState = mDocument.select("#__VIEWSTATE").attr("value");
        eventVALIDATION = mDocument.select("#__EVENTVALIDATION").attr("value");

        String title = "";
        for(Element links : element){
            if ( !TextUtils.equals("-1", links.getElementsByTag("option").attr("value")) ){
                title += links.getElementsByTag("option").attr("value") + ",";
            }
        }

        if ( !TextUtils.isEmpty(title) ){
            title = title.substring(0, title.length()-1);
            if ( isDis == 1 )//是否关闭pDialog
                mHandler.sendEmptyMessage(Code_Temp_1);

            popList1.clear();
            String [] strDim = title.split(",");
            for (int i = 0; i < strDim.length; i++) {
                popList1.add(strDim[i]);
            }
        }
    }

    public void pFun2(int isDis){
        try {
            reqContent = "__EVENTTARGET=programId&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE="+ URLEncoder.encode(viewState, "UTF-8")+
                    "&__EVENTVALIDATION="+ URLEncoder.encode(eventVALIDATION, "UTF-8")+
                    "&programId="+URLEncoder.encode(txt1.getText().toString(), "UTF-8")+
                    "&Txtroom=&TextBox2=&TextBox3=";
        }catch (Exception e){
            e.printStackTrace();
        }

        Document mDocument = Jsoup.parse(doPost(RequestMethodPost, reqContent));
        Elements divs = mDocument.select("#txtyq");
        Document divcontions = Jsoup.parse(divs.toString());
        Elements element = divcontions.getElementsByTag("option");

        viewState = mDocument.select("#__VIEWSTATE").attr("value");
        eventVALIDATION = mDocument.select("#__EVENTVALIDATION").attr("value");

        String title = "";
        for(Element links : element){
            if ( !TextUtils.equals("-1", links.getElementsByTag("option").attr("value")) ){
                title += links.getElementsByTag("option").attr("value") + ",";
            }
        }

        if ( !TextUtils.isEmpty(title) ){
            title = title.substring(0, title.length()-1);
            if ( isDis == 1 )//是否关闭pDialog
                mHandler.sendEmptyMessage(Code_Temp_2);

            popList2.clear();
            String [] strDim2 = title.split(",");
            for (int i = 0; i < strDim2.length; i++) {
                popList2.add(strDim2[i]);
            }
        }
    }

    public void pFun3(int isDis){
        try {
            reqContent = "__EVENTTARGET=txtyq&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE="+ URLEncoder.encode(viewState, "UTF-8")+
                    "&__EVENTVALIDATION="+ URLEncoder.encode(eventVALIDATION, "UTF-8")+
                    "&programId="+URLEncoder.encode(txt1.getText().toString(), "UTF-8")+
                    "&txtyq="+URLEncoder.encode(txt2.getText().toString(), "UTF-8")+
                    "&Txtroom=&TextBox2=&TextBox3=";
        }catch (Exception e){
            e.printStackTrace();
        }

        Document mDocument = Jsoup.parse(doPost(RequestMethodPost, reqContent));
        viewState = mDocument.select("#__VIEWSTATE").attr("value");
        eventVALIDATION = mDocument.select("#__EVENTVALIDATION").attr("value");
        if ( isDis == 1 )//是否关闭pDialog
            mHandler.sendEmptyMessage(Code_Temp_3);
    }

    public void pFun4(){
        try {
            reqContent = "__EVENTTARGET=&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE="+ URLEncoder.encode(viewState, "UTF-8")+
                    "&__EVENTVALIDATION="+ URLEncoder.encode(eventVALIDATION, "UTF-8")+
                    "&programId="+URLEncoder.encode(txt1.getText().toString(), "UTF-8")+
                    "&txtyq="+URLEncoder.encode(txt2.getText().toString(), "UTF-8")+
                    "&txtld="+ URLEncoder.encode( txt3.getText().toString().substring(0,1)+"层", "UTF-8")  +
                    "&Txtroom="+ txt3.getText().toString()+
                    "&ImageButton1.x=42&ImageButton1.y=7&TextBox2=&TextBox3=";
        }catch (Exception e){
            e.printStackTrace();
        }

        Message msg = new Message();
        Document mDocument = Jsoup.parse(doPost(RequestMethodPost, reqContent));
        String validePower = mDocument.select("#TextBox3").attr("value");
        if ( mDocument.toString().contains("不存在该仪表信息") || TextUtils.isEmpty(validePower)){
            msg.what = Code_Temp_5;
            msg.obj = "不存在这个房间";
        }else {
            msg.what = Code_Temp_4;
            msg.obj = validePower;
        }
        mHandler.sendMessage(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void reset(){
        pDialog.show();
        doThread(1);

        popList1.clear();
        popList2.clear();
        txt1.setText("");
        txt2.setText("");
        txt3.setText("");
        reqContent="";
        viewState="";
        eventVALIDATION = "";
        CMApplication.getInstance().userPrefer.edit().putString("Txtroom", "").commit();
        CMApplication.getInstance().userPrefer.edit().putString("txtyq", "").commit();
        CMApplication.getInstance().userPrefer.edit().putString("programId", "").commit();
        CMApplication.getInstance().userPrefer.edit().putBoolean("autoload", false).commit();

        mIncomeTxt.setValue(0);
        mHandler.sendEmptyMessageDelayed(Code_Text_Animation, 100);
    }

    @Override
    public boolean handleMessage(Message msg) {
        if ( pDialog!= null && pDialog.isShowing() ) pDialog.dismiss();

        switch (msg.what) {
            case Code_Text_Animation:
                onMeasureTxt(mIncomeTxt);
                mScrollView.sendScroll(MagicScrollView.UP, 0);
                break;

            case Code_Temp_1:
                break;

            case Code_Temp_2:
                break;

            case Code_Temp_3:
                break;

            case Code_Temp_4:
                CMApplication.getInstance().userPrefer.edit().putBoolean("autoload", true).commit();//以后启动时自动加载
                mIncomeTxt.setValue(Double.parseDouble(msg.obj.toString()));
                mHandler.sendEmptyMessageDelayed(Code_Text_Animation, 400);
                break;

            case Code_Temp_5:
                reset();
                Toast.makeText(MainActivity.this,msg.obj.toString(), Toast.LENGTH_SHORT).show();
                break;

            default:
                break;
        }
        return false;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.xmLay1:
                String[] array = (String[]) popList1.toArray(new String[popList1.size()]);
                new AlertDialog.Builder(this).setTitle("请选择")
                        .setItems(array, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                txt1.setText(popList1.get(i));
                                txt2.setText("");
                                txt3.setText("");
                                CMApplication.getInstance().userPrefer.edit().putString("programId", popList1.get(i) ).commit();

                                pDialog.show();
                                doThread(2);
                            }
                        })
                        .setNegativeButton("确定", null)
                        .show();
                break;

            case R.id.xmLay2:
                if ( TextUtils.isEmpty(txt1.getText().toString()) ){
                    Toast.makeText(MainActivity.this,"区域不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                String[] array2 = (String[]) popList2.toArray(new String[popList2.size()]);
                new AlertDialog.Builder(this).setTitle("请选择")
                        .setItems(array2, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                txt2.setText(popList2.get(i));
                                txt3.setText("");
                                CMApplication.getInstance().userPrefer.edit().putString("txtyq", popList2.get(i)).commit();

                                pDialog.show();
                                doThread(3);

                            }
                        })
                        .setNegativeButton("确定", null)
                        .show();

                break;

            case R.id.xmLay3:
                if ( TextUtils.isEmpty(txt2.getText().toString()) ){
                    Toast.makeText(MainActivity.this,"楼号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                final View editView = LayoutInflater.from(this).inflate(R.layout.edit_window, null);
                new AlertDialog.Builder(this).setTitle("请输入房间号")
                        .setView(editView)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                txt3.setText(((EditText) editView.findViewById(R.id.inputSingle)).getText().toString());
                                CMApplication.getInstance().userPrefer.edit().putString("Txtroom", txt3.getText().toString() ).commit();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();

                ActivityUtils.showKeyboard(this);

                break;
            case R.id.queryBtn:
                if ( TextUtils.isEmpty(txt1.getText().toString()) ){
                    Toast.makeText(MainActivity.this,"区域不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ( TextUtils.isEmpty(txt2.getText().toString()) ){
                    Toast.makeText(MainActivity.this,"楼号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ( TextUtils.isEmpty(txt3.getText().toString()) ){
                    Toast.makeText(MainActivity.this,"房号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ( 3 != txt3.getText().toString().length() ){
                    Toast.makeText(MainActivity.this,"房号位数不正确", Toast.LENGTH_SHORT).show();
                    return;
                }

                pDialog.show();
                doThread(4);
                break;

            case R.id.cleanBtn:
                reset();
                break;
        }
    }


}
